package kang.zhoujin.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FtpLogMail {
	public static void main(String[] args) throws SocketException, IOException, InterruptedException{
		FTPClient ftp = new FTPClient();
		while(true){
			BufferedInputStream in = null;
			try{
				ftp.connect("116.211.20.207");
				ftp.login("zhoujing","JPpNEBheT3");

				int ftpReply = ftp.getReplyCode();
				if (!FTPReply.isPositiveCompletion(ftpReply)){
					System.out.println("ftp login failed!");
					ftp.disconnect();
					Thread.sleep(3000);
					continue;
				}
				ftp.enterLocalPassiveMode();
				ftp.setFileType(FTP.BINARY_FILE_TYPE);
				ftp.changeWorkingDirectory("test");
				File file = new File("E:/dn_log");
				File[] logFiles = file.listFiles(new LogFileFilter());
				
				for(File logFile : logFiles){
					File tempFile = new File(logFile.getAbsolutePath() + ".temp");
					copyTempFile(logFile,tempFile);
					in = new BufferedInputStream(new FileInputStream(tempFile));					
					ftp.storeFile(tempFile.getName(),in);
					ftp.rename(tempFile.getName(), logFile.getName());					
					in.close();
				}
				ftp.disconnect();
			}catch (Exception e) {
				Thread.sleep(5000);
				if(ftp.isConnected())
					ftp.disconnect();
				if(in != null) in.close();
				continue;
			}			
			Thread.sleep(30000);
		}
	}

	private static void copyTempFile(File sourceFile,File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			outBuff.flush();
		} finally {
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}
	private static class LogFileFilter implements FilenameFilter{

		@Override
		public boolean accept(File dir, String name) {
			if(name.toLowerCase().endsWith(".log")) return true;
			else return false;
		}

	}
}
